class Promise2 {
  state= "pending"
  callbacks = []

  resolve(result:any){
    setTimeout(()=>{
      if(this.state !== "pending"){return}
      this.state = "fulfilled"
      this.callbacks.forEach((handle)=>{
        if(typeof handle[0] === "function"){
          //@ts-ignore
          handle[0].call(undefined,result)
        }
      })
    },0)
  }
  reject(reject:any){
    if(this.state !== "pending"){return}
    this.state = "rejected"
    setTimeout(()=>{
      this.callbacks.forEach((handle)=>{
        if(typeof handle[1] === "function"){
          //@ts-ignore
          handle[1](reject)
        }
      })
    },0)
  }
  constructor(fn:any) {
    if(typeof fn !== "function"){
      throw new Error("promise只接受一个函数")
    }
    fn(this.resolve.bind(this),this.reject.bind(this))
    
  }

  
  then(succeed?:any,fail?:any){
    const handle = [];
    if(typeof succeed === "function"){
      handle[0] = succeed
    }
    if(typeof fail === "function"){
      handle[1] = fail
    }  
    // @ts-ignore
    this.callbacks.push(handle)  
  }
}

export default Promise2
